import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private readonly jwtService: JwtService,
  ) { }
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest(); // 获取请求头
    const token = this.extractTokenFromHeader(request); // 获取请求中的token字段
    if (!token) {
      throw new UnauthorizedException('登录 token 错误，请重新登录');
    }
    try {
      const payload = await this.jwtService.verify(token, {
        secret: 'hopu',
      });
      request['user'] = payload;
    } catch (e) {
      throw new UnauthorizedException('身份过期，请重新登录');
    }
    return true;
  }
  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}

